package gov.kqqzyyy.monkey.orderpad.dialogFragment;

import android.app.DialogFragment;
import android.content.DialogInterface;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.CountDownTimer;
import androidx.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;

import gov.kqqzyyy.monkey.orderpad.R;
import gov.kqqzyyy.monkey.orderpad.mytools.MyServiceUtil;
import gov.kqqzyyy.monkey.orderpad.mytools.XMLUtils;
import gov.kqqzyyy.monkey.orderpad.object.MessageReturn;
import gov.kqqzyyy.monkey.orderpad.object.WxCXReturn;
import gov.kqqzyyy.monkey.orderpad.object.WxURLItem;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * Created by Monkey on 2017/10/5.
 * 微信二位码窗口
 */
public class WXPayDialogFragment extends DialogFragment {

    TextView mLeftTime;
    ImageView mQRCodeIMG;
    LinearLayout mLoadingLayout;
    TextView mMessageTextView;

    private Bitmap mQRBitmap;
    private CountDownTimer countDownTimer;

    private boolean isGettingPayInfo;
    private WxURLItem wxURLItem;
    private WxCXReturn wxCXReturn;

    private String SUCCESS_DDH;
    private String SUCCESS_PRICE;
    private String PATIENT_ZYH;

    private Call<String> wxurlCall;
    private Call<String> payInfoCall;
    private Call<String> jsjlCall;
    private Call<String> jsjlLogCall;
    private Call<String> fkxxCall;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {
        getDialog().requestWindowFeature(Window.FEATURE_NO_TITLE);
        getDialog().setCancelable(false);
        getDialog().setCanceledOnTouchOutside(false);
        View dialogView = inflater.inflate(R.layout.dialog_wxpay_qrcode, container, false);
        onBindDialogUI(dialogView);
        showQRBitmap();
        return dialogView;
    }

    @Override
    public void onStart() {
        super.onStart();
        startGetWXURL();
    }

    @Override
    public void onCancel(DialogInterface dialog) {
        super.onCancel(dialog);
        cancelDialog();
        if (wxurlCall != null && wxurlCall.isExecuted()) {
            wxurlCall.cancel();
        }
        if (payInfoCall != null && payInfoCall.isExecuted()) {
            payInfoCall.cancel();
        }
        if (jsjlCall != null && jsjlCall.isExecuted()) {
            jsjlCall.cancel();
        }
        if (jsjlLogCall != null && jsjlLogCall.isExecuted()) {
            jsjlLogCall.cancel();
        }
        if (fkxxCall != null && fkxxCall.isExecuted()) {
            fkxxCall.cancel();
        }
    }

    private void onBindDialogUI(View view) {
        mLeftTime = view.findViewById(R.id.paydilog_left_time_text);
        mQRCodeIMG = view.findViewById(R.id.paydilog_qrcode_img);
        mLoadingLayout = view.findViewById(R.id.paydialog_loading_layout);
        mMessageTextView = view.findViewById(R.id.paydialog_qrcode_loadfailed_tv);
    }

    public void setSUCCESS_DDH(String SUCCESS_DDH) {
        this.SUCCESS_DDH = SUCCESS_DDH;
    }

    public void setSUCCESS_PRICE(String SUCCESS_PRICE) {
        this.SUCCESS_PRICE = SUCCESS_PRICE;
    }

    public void setPATIENT_ZYH(String PATIENT_ZYH) {
        this.PATIENT_ZYH = PATIENT_ZYH;
    }

    //生成二维码图片
    private Bitmap generateBitmap() {
        QRCodeWriter qrCodeWriter = new QRCodeWriter();
        Map<EncodeHintType, String> hints = new HashMap<>();
        hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
        try {
            int QRCodeWidth = 700;
            int QRCodeHeight = 700;
            BitMatrix encode = qrCodeWriter.encode(wxURLItem.getUrl(), BarcodeFormat.QR_CODE, QRCodeWidth, QRCodeHeight, hints);
            int[] pixels = new int[QRCodeWidth * QRCodeHeight];
            for (int i = 0; i < QRCodeHeight; i++) {
                for (int j = 0; j < QRCodeWidth; j++) {
                    if (encode.get(j, i)) {
                        pixels[i * QRCodeWidth + j] = 0x00000000;
                    } else {
                        pixels[i * QRCodeWidth + j] = 0xffffffff;
                    }
                }
            }
            return Bitmap.createBitmap(pixels, 0, QRCodeWidth, QRCodeWidth, QRCodeHeight, Bitmap.Config.RGB_565);
        } catch (WriterException e) {
            e.printStackTrace();
        }
        return null;
    }

    public void setmQRBitmap(Bitmap mQRBitmap) {
        this.mQRBitmap = mQRBitmap;
        showQRBitmap();
    }

    public void showQRBitmap() {
        if (mQRBitmap != null) {
            mLoadingLayout.setVisibility(View.GONE);
            mMessageTextView.setVisibility(View.GONE);
            mQRCodeIMG.setVisibility(View.VISIBLE);
            mQRCodeIMG.setImageBitmap(mQRBitmap);
            doCountDown();
        } else {
            mQRCodeIMG.setVisibility(View.INVISIBLE);
            mLoadingLayout.setVisibility(View.VISIBLE);
            mMessageTextView.setVisibility(View.GONE);
        }
    }

    public void setMessage(String message) {
        mQRCodeIMG.setVisibility(View.INVISIBLE);
        mLoadingLayout.setVisibility(View.GONE);
        mMessageTextView.setVisibility(View.VISIBLE);
        mMessageTextView.setText(message);
    }

    public void cancelDialog() {
        if (countDownTimer != null) {
            countDownTimer.cancel();
        }
        getDialog().dismiss();
    }

    public void startGetWXURL() {
        if (getDialog().isShowing()) {
//            new MyGetWXURLTask().execute(SUCCESS_DDH, SUCCESS_PRICE.replace(".", ""));
            doGetWXURL(SUCCESS_DDH, SUCCESS_PRICE.replace(".", ""));//测试用假数据
        }
    }

    //微信二维码倒计时
    private void doCountDown() {
        countDownTimer = new CountDownTimer(300000, 1000) {
            @Override
            public void onTick(long l) {
                String leftTime = "剩余时间：" + l / 1000 + "秒";
                mLeftTime.setText(leftTime);
                if (!isGettingPayInfo) {
//                    new MyGetPayInfoTask().execute(wxURLItem.getOut_trade_no());
                    doGetPayInfo(wxURLItem.getOut_trade_no());
                }
            }

            @Override
            public void onFinish() {
                mLeftTime.setText("二维码已失效!");
//                new MyGetWXURLTask().execute(SUCCESS_DDH, SUCCESS_PRICE);
                doGetWXURL(SUCCESS_PRICE, SUCCESS_PRICE);
            }
        };
        countDownTimer.start();
    }

    private void doGetWXURL(String productID, String total) {
        wxurlCall = MyServiceUtil.getWXURLCall(productID, total);
        Callback<String> callback = new Callback<String>() {
            @Override
            public void onResponse(Call<String> call, Response<String> response) {
                String result = response.body();
                result = result.replace("\"", "");
                String[] xmlPart = result.split(",");
                wxURLItem = new WxURLItem();
                wxURLItem.setState(xmlPart[0]);
                wxURLItem.setProductId(xmlPart[1]);
                wxURLItem.setOut_trade_no(xmlPart[2]);
                wxURLItem.setUrl(xmlPart[3]);
                if (xmlPart.length == 5) {
                    wxURLItem.setMessage(xmlPart[6]);
                }
                String qqsj = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.CHINA).format(new Date());
                doSaveJSJL(PATIENT_ZYH, SUCCESS_DDH, wxURLItem.getOut_trade_no(), wxURLItem.getUrl(), qqsj, SUCCESS_PRICE);
            }

            @Override
            public void onFailure(Call<String> call, Throwable t) {
                setMessage("二维码获取失败！");
            }
        };
        wxurlCall.enqueue(callback);
    }

    private void doGetPayInfo(String out_trade_no) {
        isGettingPayInfo = true;
        payInfoCall = MyServiceUtil.getPayInfoCall(out_trade_no);
        Callback<String> callback = new Callback<String>() {
            @Override
            public void onResponse(Call<String> call, Response<String> response) {
                isGettingPayInfo = false;
                String result = response.body();
                result = result.replace("\"", "");
                String[] xmlResult = result.split(",");
                if (!xmlResult[0].equals("FAIL")) {
                    wxCXReturn = XMLUtils.readXML(xmlResult[1], WxCXReturn.class);
                    Toast.makeText(getActivity(), "付款成功！", Toast.LENGTH_SHORT).show();
                    cancelDialog();
                    String jlsj = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.CHINA).format(new Date());
//                    new MySaveJSJLLOGTask().execute(PATIENT_ZYH, SUCCESS_DDH, jlsj, xmlResult[1]);
                    doSaveJSJLLog(PATIENT_ZYH, SUCCESS_DDH, jlsj, xmlResult[1]);
                }

            }

            @Override
            public void onFailure(Call<String> call, Throwable t) {
                isGettingPayInfo = false;
                Toast.makeText(getActivity(), "获取付款状态失败：" + t.toString(), Toast.LENGTH_SHORT).show();
            }
        };
        payInfoCall.enqueue(callback);

    }

    private void doSaveJSJL(String brzyh, String dcddh, String shddh, String wxurl, String qqsj, String fkje) {
        jsjlCall = MyServiceUtil.saveJSJLCall(brzyh, dcddh, shddh, wxurl, qqsj, fkje);
        Callback<String> callback = new Callback<String>() {
            @Override
            public void onResponse(Call<String> call, Response<String> response) {
                String result = response.body();
                Gson gson = new Gson();
                MessageReturn messageReturn = gson.fromJson(result, new TypeToken<MessageReturn>() {
                }.getType());
                if (messageReturn != null) {
                    switch (messageReturn.getMsg()) {
                        case "FAIL":
                            Toast.makeText(getActivity(), "保存结算信息失败！", Toast.LENGTH_SHORT).show();
                            cancelDialog();
                            break;
                        case "EXIST":
                            Toast.makeText(getActivity(), "结算信息已存在！", Toast.LENGTH_SHORT).show();
                            cancelDialog();
                            break;
                        case "SUCCESS":
                            Toast.makeText(getActivity(), "二维码信息保存成功！", Toast.LENGTH_SHORT).show();
                            Bitmap QRCodeBitmap = generateBitmap();
                            if (QRCodeBitmap != null) {
                                setmQRBitmap(QRCodeBitmap);
                            }
                            break;
                    }
                }
            }

            @Override
            public void onFailure(Call<String> call, Throwable t) {
                cancelDialog();
                Toast.makeText(getActivity(), "保存结算信息失败：" + t.toString(), Toast.LENGTH_SHORT).show();
            }
        };
        jsjlCall.enqueue(callback);
    }

    private void doSaveJSJLLog(String brzyh, String dcddh, String jlsj, String fhjg) {
        jsjlLogCall = MyServiceUtil.saveJSJLLogCall(brzyh, dcddh, jlsj, fhjg);
        Callback<String> callback = new Callback<String>() {
            @Override
            public void onResponse(Call<String> call, Response<String> response) {
                String result = response.body();
                Gson gson = new Gson();
                MessageReturn messageReturn = gson.fromJson(result, new TypeToken<MessageReturn>() {
                }.getType());
                if (messageReturn != null) {
                    switch (messageReturn.getMsg()) {
                        case "FAIL":
                            Toast.makeText(getActivity(), "支付信息保存失败！", Toast.LENGTH_SHORT).show();
                            break;
                        case "EXIST":
                            Toast.makeText(getActivity(), "支付信息已存在！", Toast.LENGTH_SHORT).show();

                            break;
                        case "SUCCESS":
                            Toast.makeText(getActivity(), "支付信息保存成功！", Toast.LENGTH_SHORT).show();
                            doSaveFKXX(SUCCESS_DDH, jlsj, wxCXReturn.getOpenid(), wxCXReturn.getIs_subscribe());
                            break;
                    }
                }
            }

            @Override
            public void onFailure(Call<String> call, Throwable t) {
                Toast.makeText(getActivity(), "支付信息保存失败：" + t.toString(), Toast.LENGTH_SHORT).show();
            }
        };
        jsjlLogCall.enqueue(callback);
    }

    private void doSaveFKXX(String dcddh, String fksj, String zfwxbz, String wxhgz) {
        fkxxCall = MyServiceUtil.saveFKXXCall(dcddh, fksj, zfwxbz, wxhgz);
        Callback<String> callback = new Callback<String>() {
            @Override
            public void onResponse(Call<String> call, Response<String> response) {
                String result = response.body();
                Gson gson = new Gson();
                MessageReturn messageReturn = gson.fromJson(result, new TypeToken<MessageReturn>() {
                }.getType());
                if (messageReturn != null && messageReturn.getMsg().contains("SUCCESS")) {
                    Toast.makeText(getActivity(), "付款信息已保存成功！", Toast.LENGTH_SHORT).show();
//                    ((OrderCheckActivity2) getActivity()).doFlushOrderList();
                } else {
                    Toast.makeText(getActivity(), "保存付款信息出错，请联系信息科！", Toast.LENGTH_SHORT).show();
                }

            }

            @Override
            public void onFailure(Call<String> call, Throwable t) {
                Toast.makeText(getActivity(), "保存付款信息出错：" + t.toString(), Toast.LENGTH_SHORT).show();
            }
        };
        fkxxCall.enqueue(callback);
    }
}
